package com.sn.campus.utils;


import com.sn.campus.nettyserver.NettyServerHandler;
import com.sn.campus.serviceImpl.OperationServiceImpl;
import io.netty.channel.ChannelId;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @ProjectName: netty_socket
 * @Package: com.socket.server.utils
 * @ClassName: ${CLASS_NAME}
 * @Author: xiahuihui
 * @Description: ${description}
 * @Date: 2020/6/11 0011 13:06
 * @Version: 1.0
 */


public class PeriodicDuty implements Runnable {

    private NettyServerHandler nettyServerHandler = new NettyServerHandler();

    private Object lock;
    private Logger log = LogManager.getLogger(getClass());
    //创建一个对应的设备队列
    public static LinkedBlockingQueue<ChannelId> channelIdQueue = new LinkedBlockingQueue<>(1000);

    private LinkedBlockingQueue<String> reportFreqs = new LinkedBlockingQueue<String>(1000);

    private String deviceId;

    String[] white = {"879", "887", "899", "909", "914", "934", "940", "947", "955", "959", "962", "972", "977", "981",
            "990", "1001", "1003", "1009", "1017", "1025", "1027", "1037", "1051", "1057", "1065", "1067", "1072",
            "1077"};

    @Resource
    OperationServiceImpl operationService;

    public void startExecution() {
        log.info("我到了周期任务类中");

    }


    public PeriodicDuty(Object lock, String deviceId) {
        this.lock = lock;
        this.deviceId = deviceId;
    }

    /**
     * @param
     * @Method: 执行周期任务
     * @Author: cainiaoxiaohuihui
     * @Version: 1.0.0
     * @Description
     * @Return:
     * @Exception:
     * @Date: 2020/6/11 0011 17:41
     */

    public synchronized void runningStart() {
        List<ChannelId> channelIds = new ArrayList<>();
        NettyServerHandler nettyServerHandler = new NettyServerHandler();

        while (true) {
//            if (NettyServerHandler.getDeviceMap().isEmpty()) {
//                try {
//                    Thread.sleep(10000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                continue;
//            }
            //执行扫台任务
//            log.info("目前channelIdQueue的数据有：" + channelIds.toString());
//            NettyServerHandler.getChannelMap().forEach((key, value) -> channelIdQueue.add(key));
//
//            ChannelId ch = channelIdQueue.poll();
//            System.out.println("目前连接的设备：" + ch + "----------------------");
            String msg = "scanfreqs#870-1080#0";
            try {

                nettyServerHandler.channelWrite(NettyServerHandler.getDeviceMap().get(deviceId), msg);
//                lock.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
//            for (int i = 0; i < channelIds.size(); i++) {
//                System.out.println("目前连接的设备：" + channelIds.get(i) + "----------------------");
//                String msg = "scanfreqs#870-1080#0";
//                try {
//                    nettyServerHandler.channelWrite(channelIds.get(i), msg);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }

//            String id = null;
//            try {
//                id = NettyServerHandler.deviceQueue.poll();
//            } catch (NullPointerException e) {
//                e.printStackTrace();
//                log.error("目前设备队列暂时没有数据！！！");
//                continue;
//            }
//            if (id != null && !id.isEmpty()) {
//                String msg = "scanfreqs#870-1080#0";
//                try {
//                    nettyServerHandler.channelWrite(NettyServerHandler.getDeviceMap().get(id), msg);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    log.error("执行周期任务下发扫台命令操作异常！！！");
//                    continue;
//                }
//            } else {
//                continue;
//            }

//            deviceId.clear();

//            try {
//                System.out.println("打印任务队列的数据：" + MessageUtil.reportFreqs);
//            } catch (Exception e) {
//                System.out.println("暂时没有任务");
//            }
//
//
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //执行调频任务
//            NettyServerHandler.

            log.info("打印消息队列中的数据" + NettyServerHandler.reportFreqs);
            String poll = null;
            try {
                poll = NettyServerHandler.reportFreqs.poll();
            } catch (NullPointerException e) {
                e.printStackTrace();
                log.error("目前消息队列中暂时没有数据！！");
                continue;
            }
            log.info("打印取出的任务队列数据：" + poll);
            if (poll != null && !poll.isEmpty()) {
                String[] deviceMes = poll.split("@");
                String device = deviceMes[0];
                String message = deviceMes[1];
                String[] s = message.split("#");
//                synchronized (dutyLock) {
                for (int i = 0; i < s.length; i++) {
                    String sendMes = "tune#" + s[i] + "#2";
                    log.info("执行周期任务调频开始！！！");

                    try {
                        nettyServerHandler.channelWrite(NettyServerHandler.getDeviceMap().get(device), sendMes);

                        Thread.sleep(30000);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("执行调频周期任务发送消息异常！！！", e);
                        continue;
                    }
//                            dutyLock.wait();
                }
//                }
//
//                try {
//                    Thread.sleep(10000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                //执行录音任务


//                String[] deviceMes = mes.split("@");
//                String device = deviceMes[0];
//                String message = deviceMes[1];
//                String[] s = message.split("#");
//                for (int i = 0; i < s.length; i++) {
//                    String sendMes = "recording#" + s[i] + "#30";
//                    System.out.println("执行周期任务录音开始！！！！");
//                    try {
//                        nettyServerHandler.channelWrite(NettyServerHandler.getDeviceMap().get(device), sendMes);
//                        Thread.sleep(100);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        log.error("执行调频周期任务发送消息异常！！！", e);
//
//                    }
//                }
//
//            }
//                try {
////                Thread.sleep(1200000);
//                    Thread.sleep(300000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            MessageUtil.reportFreqs.clear();
            }
        }

    }


    @Override
    public void run() {
        synchronized (lock) {
            log.info("创建新的线程开始执行周期任务！！！");
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            NettyServerHandler nettyServerHandler = new NettyServerHandler();
            int cycle = 0;
            while (true) {
                //执行周期任务
                String s1 = NettyServerHandler.deviceScanfreqs.get(deviceId);
                reportFreqs.add(deviceId + "@" + s1);
                log.info("打印消息队列中的数据" + reportFreqs.toString());
                String poll = reportFreqs.poll();
                log.info("打印取出的任务队列数据：" + poll);
                if (poll == null && poll.isEmpty()) {
                    log.info("暂时任务队列中没有消息！！！");
                    String msg = "scanfreqs#870-1080#0";
                    try {
                        nettyServerHandler.channelWrite(NettyServerHandler.getDeviceMap().get(deviceId), msg);
                        log.info("已经将扫台命令下发！！！，开始等待！！！");
                    } catch (Exception e) {
                        e.printStackTrace();
                        try {
                            log.info("终端掉线，等待重连！！！！");
                            lock.wait();
                            log.info("终端重连成功，继续任务！！！");
                            continue;
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    }
                    try {
                        Thread.sleep(75000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    log.info("小哥已被睡醒了！开始执行接下来的任务！！！！");
                }
                if (poll != null && !poll.isEmpty()) {
                    String[] deviceMes = poll.split("@");
                    String device = deviceMes[0];
                    String message = deviceMes[1];
                    String[] s = message.split("#");
//                synchronized (dutyLock) {
                    log.info("执行周期任务调频开始！！！");
                    for (int i = 0; i < s.length; i++) {
                        log.info(NettyServerHandler.getDeviceStatus().get(device));
                        if (NettyServerHandler.getDeviceMap().get(device) != null && NettyServerHandler.getDeviceStatus().get(device).equals("true")) {
                            String tuneMes = "tune#" + s[i] + "#2";


                            try {
                                log.info("向设备" + device + "：" + NettyServerHandler.getDeviceMap().get(device) + "发送调频任务！！！！");
                                nettyServerHandler.channelWrite(NettyServerHandler.getDeviceMap().get(device), tuneMes);
                                Thread.sleep(10000);
//                                lock.wait();
                                log.info("小哥已被唤醒！开始执行接下来的任务！！！！");
                            } catch (Exception e) {
                                e.printStackTrace();
                                log.error("执行调频周期任务发送消息异常！！！", e);
                                continue;
                            }
                            List<String> whiteList = Arrays.asList(white);
                            //判断该频率是否为白名单；
                            if (whiteList.contains(s[i])) {
                                if (cycle % 6 == 0) {
                                    try {
                                        startRecord(s[i],device);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        log.info("发送消息到客户端异常！！！");
                                    }
                                }
                                else
                                    continue;
                            }
                            try {
                                startRecord(s[i],device);
                            } catch (Exception e) {
                                e.printStackTrace();
                                log.info("发送消息到客户端异常！！！");

                            }

                        }else {
                        log.info("目前该设备已经断开连接，等待恢复连接，继续执行任务！！！");
                        try {
                            NettyServerHandler.getDeviceStatus().put(device, "false");
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                    }
                }
                NettyServerHandler.reportFreqs.clear();

                cycle++;
                log.info("一个周期结束！！！！睡一觉去！！！");
                try {
                    Thread.sleep(1000*60*25);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                log.info("睡醒了，开工！！！！");


            }
        }
    }

    public void startRecord(String frequency,String device) throws Exception {

        log.info("执行周期任务录音开始！！！");
        String recordMes = "recording#" + frequency + "#30";
        try {
            log.info("向设备" + device + "：" + NettyServerHandler.getDeviceMap().get(device) + "发送录音任务！！！！");
            nettyServerHandler.channelWrite(NettyServerHandler.getDeviceMap().get(device), recordMes);
            Thread.sleep(35000);
//                                lock.wait();
            log.info("小哥已被唤醒！开始执行接下来的任务！！！！");
        } catch (Exception e) {

            log.error("执行录音周期任务发送消息异常！！！", e);
            throw new Exception();

        }
    }

    public void test() {

    }

    public void sendMessage(String msg) throws Exception {

        nettyServerHandler.channelWrite(NettyServerHandler.getDeviceMap().get(deviceId), msg);

    }


}
